前言

集合就是数学中的集合概念, 只不过用到了编程语言中. 也就是Set类

概念: 由一组无序且唯一的项组成.

正文

下面就让我们来实现Set类

class MySet{

  items = {} //存放数据的对象, 这次使用的是对象来存放, 而不是数组, 主要是对象更方便

  //集合是否存放了这个数据
  has(value){
    return this.items.hasOwnProperty(value)
  }

  //在集合中添加一个数据
  add(value){
    if(!this.has(value)){
      this.items.
    }
  }

  //移除集合中某个元素
  remove(value){
    if(!this.has(value)){
      delete this.items[value]
      return true
    }
    return false
  }

  //移除集合中所有元素
  clear(){
    this.items = {}
  }

  //获得集合中元素个数
  size(){
    return Object.keys(this.items).length
  }

  //获得集合中所有元素
  values(){
    return Object.keys(this.items)
  }

  //下面实现集合的 并集 交集 合集 子集

  //并集
  union(otherSet){
    const unionSet = new MySet()
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      unionSet.add(selfVal)
    }
    const otherSetValues = otherSet.values()
    for(let otherVal of otherSetValues){
      unionSet.add(otherVal)
    }
    return unionSet
  }

  //交集
  intersection(otherSet){
    const intersectionSet = new MySet()
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      if(otherSet.has(selfVal)){
        intersectionSet.add(selfVal)
      }
    }
    return intersectionSet
  }

  //差集(本集合和另一个集合不同的元素)
  difference(otherSet){
    const differenceSet = new MySet()
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      if(!otherSet.has(selfVal)){
        differenceSet.add(selfVal)
      }
    }
    return differenceSet
  }

  //子集(判断本集合是否是另一个集合的子集)
  isSub(otherSet){
    if(this.size()>otherSet.size()){
      return false
    }
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      if(!otherSet.has(selfVal)){
        return false
      }
    }
    return true
  }
  
}

注意: ① in关键字遍历items对象时, 会把items继承的类属性也找出来, 而hasOwnProperty方法of关键字 只会遍历item对象本身的属性, 所以我没用in关键字

结尾

今天我们实现了集合这种数据结构, 大家对集合这种数据结构也有了更深刻的认识.

THE END
推荐文章
  • 去除input和textarea点击选中框

  • php中__autoload和spl_autoload_register的区别

  • Webpack打包后文件报错 $ is not defined or jQuery is not defined

  • 黄帝内经-第22篇-脏气法时论篇(1)

  • python下载中国mooc课程实战

  • linux禁止root用户登陆并指定特定用户登陆

  • 黄帝内经-第39篇-举痛论篇(1)

  • 微信开店全攻略

评论 共0条
开启精彩搜索

热门搜索

暂无

历史搜索

用户名/邮箱/手机号
密码
用户名
密码
重复密码
邮箱/手机号
验证码
发送验证码
59秒后可重发
注册
找回密码
邮箱/手机号
验证码
发送验证码
59秒后可重发
新密码
重复密码
请选择支付方式
余额支付

购买将消耗【10

微信支付
微信扫码支付 0 元
[ 04分50秒 ]
请使用微信扫一扫
扫描二维码支付
支付宝支付
支付宝扫码支付 0 元
[ 04分50秒 ]
请使用支付宝扫一扫
扫描二维码支付
已完成支付
未完成支付

请输入验证码

点击验证码可以刷新

你确认吗?

确认

2024年10月1日

0字

0字

2024年10月

0字

新增

0字

新增

0字

0字

新增

0字

0字

新增

0字

0字

新增

0字

0字

新增

0字

0字

新增

0字

0字

新增

0字

0字

0字

新增

0字

0字

0字

0字

新增

0字

0字